package demo.service;

import demo.Result;
import demo.entity.PM;
import demo.entity.User;
import demo.repository.PMRepository;
import demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 私信 Service
 *
 * @author 肖溥博文
 * @version 1.4
 */
@Service
public class PMService {

    @Autowired
    PMRepository pmRepository;
    @Autowired
    UserRepository userRepository;

    /**
     * 发送私信
     *
     * @param senderUid    发送者 uid
     * @param recipientUid 接收者 uid
     * @param content      内容
     * @return 结果对象，若成功则包含私信对象
     */
    public Result sendPM(Long senderUid, Long recipientUid, String content) {
        User sender = userRepository.findUserByUid(senderUid);
        if (sender == null) {
            return Result.error("发送者不存在，私信发送失败");
        }

        User recipient = userRepository.findUserByUid(recipientUid);
        if (recipient == null) {
            return Result.error("接受者不存在，私信发送失败");
        }

        PM pm = new PM();
        pm.setSenderUid(senderUid);
        pm.setRecipientUid(recipientUid);
        pm.setContent(content);
        pm.setSendingTime(new Date());

        pmRepository.save(pm);
        return Result.success("私信发送成功", pm);
    }

    /**
     * 列出单向发送的所有私信
     *
     * @param senderUid    发送人 uid
     * @param recipientUid 接收人 uid
     * @return 结果对象，包括私信对象的数组
     */
    public Result listPMsOneSide(Long senderUid, Long recipientUid) {
        return Result.success("私信查询成功", pmRepository.findAllBySenderUidAndRecipientUid(senderUid, recipientUid));
    }

    /**
     * 列出两人所发的所有私信
     *
     * @param uid1 用户 1 的 uid
     * @param uid2 用户 2 的 uid
     * @return 结果对象，包括私信对象的数组
     */
    public Result listPMs(Long uid1, Long uid2) {
        return Result.success("私信查询成功", pmRepository.fetchPMsByUids(uid1, uid2));
    }

    /**
     * 查询消息列表所有的联系人
     *
     * @param uid 用户 id
     * @return 结果对象，包含联系人 uid 的数组
     */
    public List<Long> listLatestContactUidsByUid(Long uid) {
        return pmRepository.fetchLatestContactsByUid(uid);
    }

    /**
     * 查询消息列表的所有消息编号
     *
     * @param uid 用户 id
     * @return 结果对象，包含消息 id 的数组
     */
    public List<Long> listLatestContactPMIdByUid(Long uid) {
        return pmRepository.fetchLatestPMIdByUid(uid);
    }

    /**
     * 按 私信 id 查找私信对象
     *
     * @param id 私信 id
     * @return 私信对象
     */
    public PM getPMById(Long id) {
        return pmRepository.findPMById(id);
    }
}
